<?php
namespace order\impl;
use order\Order;
use tool\Price;

class Pt extends Order {

    public function make_pre($pre_order)
    {
        $price=new Price();
        $goods_list=$pre_order['goods_list'];
        if(count($goods_list)!=1){
            e("参团参数错误");
        }
        if($goods_list[0]['buynumber']!=1){
            e("参团参数错误");
        }
        foreach ($goods_list as $_goods){
            $goods=model("goods")->where("id",$_goods['id'])->find();
            $price->changeprice($goods['price'],"购买{$goods['name']} 数量:{$_goods['buynumber']}",$_goods['buynumber']);
        }
        $params=$pre_order['params'];

        $pt_group_id=$params['pt_group_id'];
        $prorder=model("ptOrder")->where('user_id',$pre_order['user_id'])->where("pt_group_id",$pt_group_id)->find();
        if(!empty($prorder)){
            e("您已参团,不可重复参团");
        }
        $group=model("ptGroup")->where("id",$pt_group_id)->find();
        if($group['cnumber']<$group['number']&& time()>$group['end_timestamp']&&$group['status']==0){
            model("ptGroup")->where("id",$pt_group_id)->update(['status'=>2]);
        }

        if($group['status']!=0){
            e("该团状态不允许拼团");
        }
        $price->changeprice(-$group['discount'],"拼团优惠");
        $pre_order['discount']=$group['discount'];
        $pre_order['price_list']=$price->getprice_list();
        $pre_order['totalprice']=$price->gettotalprice();
        $pre_order['extend']=["pt_group_id"=>$pt_group_id];
        $pre_order['isused']=0;

        return $pre_order;
    }

    public function make($order)
    {
        $price=new Price($order['price_list']);
        $order['price_list']=$price->getprice_list();
        $order['totalprice']=$price->gettotalprice();

        return $order;
    }

    public function notify($order)
    {
        $orderno=$order['orderno'];
        $extend=json_decode($order['extend'],true);
        $pt_group_id=$extend['pt_group_id'];
        $prorder=model("ptOrder")->where('orderno',$orderno)->find();
        if(!empty($prorder)){
            return;
        }
        model("ptOrder")->insert(['orderno'=>$orderno,"pt_group_id"=>$pt_group_id,"user_id"=>$order['user_id'],"time"=>now()]);
        $cnumber=model("ptOrder")->where("pt_group_id",$pt_group_id)->count();
        model("ptGroup")->where("id",$pt_group_id)->update(["cnumber"=>$cnumber]);
        $group=model("ptGroup")->where("id",$pt_group_id)->find();
        if($cnumber>=$group['number']){
            model("ptGroup")->where("id",$pt_group_id)->update(['status'=>1]);
        }
        model("order")->where("orderno",$orderno)->update(["status"=>1,"ispay"=>1]);
        return "";
    }
}